package com.rrd.hive.udf;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.hive.ql.exec.UDF;

/**
 * 按excel的rate函数计算利率
 * @author liubaoxin
 *
 */
public class TestExcelRateUDF extends UDF {

	/**迭代次数*/
	public static int LOOPNUM=1000;
	/**最小差异*/
	public static final double MINDIF=0.00000001;
	/**
	* @desc 使用方法参考main方法
	* @param cashFlow
	资金流
	* @return 收益率
	*/
	public static double getIrr(List<Double> cashFlow){
	double flowOut=cashFlow.get(0);
	double minValue=0d;
	double maxValue=1d;
	double testValue=0d;
	while(LOOPNUM>0){
	testValue=(minValue+maxValue)/2;
	double npv=NPV(cashFlow,testValue);
	if(Math.abs(flowOut+npv)<MINDIF){
	break;
	}else if(Math.abs(flowOut)>npv){
	maxValue=testValue;
	}else{
	minValue=testValue;
	}
	LOOPNUM--;
	}
	return testValue;
	}
	public static double NPV(List<Double> flowInArr,double rate){
	double npv=0;
	for(int i=1;i<flowInArr.size();i++){
	npv+=flowInArr.get(i)/Math.pow(1+rate, i);
	}
	return npv;
	}
	 private static String formatDouble(double d) {
         NumberFormat nf = NumberFormat.getInstance();
         //设置保留多少位小数
         nf.setMaximumFractionDigits(200);
          // 取消科学计数法
         nf.setGroupingUsed(false);
         //返回结果
         return nf.format(d);
     }
	 
	public static void main(String[] args) {
	double flowOut=-950d;
	List<Double> flowInArr=new ArrayList<Double>();
	flowInArr.add(flowOut);
	flowInArr.add(501d);
	double ir = TestExcelRateUDF.getIrr(flowInArr)*12;
	System.out.println(ir);
 
	System.out.println(formatDouble(ir));
	ir =0/0;
	System.out.println(formatDouble(ir));
	}

}
